package com.diaohaiwen.framework.db.generator;

import com.mybatisflex.codegen.config.EntityConfig;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.config.PackageConfig;
import com.mybatisflex.codegen.entity.Column;
import com.mybatisflex.codegen.entity.Table;
import com.mybatisflex.codegen.generator.IGenerator;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刁海文
 * @since 2023/7/19 15:39
 * @Remark
 */
public class MyEntityGenerator implements IGenerator {
    private String templatePath = "/templates/enjoy/entity.tpl";
    ;

    @Override
    public String getTemplatePath() {
        return templatePath;
    }

    @Override
    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }

    @Override
    public void generate(Table table, GlobalConfig globalConfig) {

        if (!globalConfig.isEntityGenerateEnable()) {
            return;
        }

        PackageConfig packageConfig = globalConfig.getPackageConfig();
        EntityConfig entityConfig = globalConfig.getEntityConfig();

        String entityPackagePath = packageConfig.getEntityPackage().replace(".", "/");
        File entityJavaFile = new File(packageConfig.getSourceDir(), entityPackagePath + "/" +
                table.buildEntityClassName() + ".java");


        if (entityJavaFile.exists() && !entityConfig.isOverwriteEnable()) {
            return;
        }

        List<Column> columns = table.getColumns().stream()
                .filter(c -> !c.getProperty().equals("id"))
                .filter(c -> !c.getProperty().equals("created"))
                .filter(c -> !c.getProperty().equals("createdBy"))
                .filter(c -> !c.getProperty().equals("updatedBy"))
                .filter(c -> !c.getProperty().equals("updated"))
                .collect(Collectors.toList());

        table.setColumns(columns);

        Map<String, Object> params = new HashMap<>(4);
        params.put("table", table);
        params.put("entityConfig", entityConfig);
        params.put("packageConfig", packageConfig);
        params.put("javadocConfig", globalConfig.getJavadocConfig());

        globalConfig.getTemplateConfig().getTemplate().generate(params, templatePath, entityJavaFile);

        System.out.println("Entity ---> " + entityJavaFile);

    }
}
